<template>
  <el-drawer
    v-model="dialogVisible"
    :show-close="false"
    size="600px"
    :wrapperClosable="false"
    :before-close="handleClose"
    @open="handleOpen">
    <template #header>
      <div class="search-custom-title-nav">
        <p class="title">{{title}}</p>
        <div>
          <el-button @click="handleClose(true)">关闭</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleConfirm">确定</el-button>
        </div>
      </div>
    </template>
    <el-scrollbar class="search-main-wrap">
      <div>
        <el-form
          ref="formRef" :model="form"
          :rules="rules"
          label-suffix="："
          label-position="top"
          label-width="100px"
          inline>
          <el-form-item label="账户名称" prop="accountName">
            <el-input
              v-model.trim="form.accountName"
              size="small"
              clearable
              class="input-width"
              maxlength="15"
              v-trim
              show-word-limit
              placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-input
              v-model.trim="form.realName"
              size="small"
              clearable
              class="input-width"
              maxlength="10"
              v-trim
              show-word-limit
              placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model.trim="form.phone"
              size="small"
              clearable
              class="input-width"
              maxlength="11"
              v-trim
              show-word-limit
              placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model.trim="form.email"
              size="small"
              clearable
              v-trim
              class="input-width"
              placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <div class="input-width">
              <el-switch
                v-model="form.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="启用"
                inactive-text="禁用"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <div class="module-title">关联角色</div>
        <div class="tree-wrap">
          <el-skeleton v-if="getResourceLoading"/>
          <div>
            <el-checkbox
              v-model="checkAll"
              size="default"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange">
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="checkedRoles"
              size="default"
              @change="handleCheckedRoleChange"
            >
              <div class="role-wrap">
                <div v-for="item in resourceList" :key="item.value" class="role-item">
                  <el-checkbox :label="item.value" :value="item.value">
                    <span class="role-label text-ellipsis">{{item.label}}</span>
                  </el-checkbox>
                </div>
              </div>
            </el-checkbox-group>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </el-drawer>
</template>

<script setup>
import { ref, defineProps, defineEmits, nextTick, computed } from 'vue'
import { useDialogCommonData, emitBaseEventList } from '@/composables/dialog-common'
import { awaitWrap, elFormValidate } from '@/utils'
import { SUCCESS_CODE } from '@/constants'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAccountRoles, saveAccountInfo } from '@/api/account-management'
import { validateEmailRegExp, validatePhoneRegExp } from '@/utils/commonValidate'
import { getRoleList } from '@/api/role-management'

// ---------------------props-------------------
const props = defineProps({
  visible: Boolean, // 可见性
  pdata: { // 数据，同defaultForm表单
    type: Object,
    default () {
      return null
    }
  }
})

// emit
const emit = defineEmits([...emitBaseEventList])

// form组件实例
const formRef = ref() // this.$refs.form

// 是否是编辑
const isEdit = computed(() => !!props.pdata)

// ---------------------el-Dialog组件需要一些参数-------------------
const { dialogVisible, handleClose } = useDialogCommonData(props, emit)
const title = ref('')
// 打开
const handleOpen = () => {
  title.value = isEdit.value ? '编辑' : '新增'
  initForm()
  initResource()
}

// ---------------------form表单内容-------------------
// 默认表格内容
const defaultForm = {
  fid: null,
  accountName: null,
  realName: null,
  phone: null,
  email: null,
  status: null
}

const form = ref({ ...defaultForm })
const rules = ref({
  accountName: [{ required: true, message: '请输入账号名称', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: validatePhoneRegExp(), message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { pattern: validateEmailRegExp(), message: '请输入正确的邮箱', trigger: 'blur' }
  ]
})
// 初始化form
const initForm = () => {
  form.value = isEdit.value ? { ...props.pdata } : { ...defaultForm }
  nextTick(formRef.value.clearValidate)
}

// ---------------------角色列表相关内容-------------------
// 权限资源数据列表
const resourceList = ref([])
// 选中的资源
const checkedRoles = ref([])
// 全选
const checkAll = ref(false)
// 半选
const isIndeterminate = ref(false)
// 获取资源loading
const getResourceLoading = ref(false)

// 初始化资源
const initResource = () => {
  resourceList.value = []
  checkedRoles.value = []
  isIndeterminate.value = false
  checkAll.value = false
  // 假数据
  const isMock = false
  if (isMock) {
    const mockData = []
    for (let i = 1; i <= 30; i++) {
      mockData.push({
        roleId: i,
        checked: i % 3 === 0,
        roleName: `角色${i}`
      })
    }
    dealResourceData(mockData)
  } else {
    isEdit.value ? getResourceList() : getAllRoleList()
  }
}
// 全选变化
const handleCheckAllChange = (val) => {
  checkedRoles.value = val ? resourceList.value.map(v => v.value) : []
  isIndeterminate.value = false
}
// 角色选中变化
const handleCheckedRoleChange = (val) => {
  const checkedLen = val.length
  const allLen = resourceList.value.length
  checkAll.value = checkedLen === allLen
  isIndeterminate.value = checkedLen > 0 && checkedLen < allLen
}
// 获取资源
const getResourceList = async () => {
  getResourceLoading.value = true
  const { res } = await awaitWrap(getAccountRoles(props.pdata?.fid || ''))
  if (res?.statusCode === SUCCESS_CODE) {
    // 格式化数据
    dealResourceData(res.data)
  }
  getResourceLoading.value = false
}

// 获取所有角色列表
const getAllRoleList = async () => {
  const { res } = await awaitWrap(getRoleList({
    currentPage: 1,
    pageSize: 500
  }))
  if (res?.statusCode === SUCCESS_CODE) {
    // 格式化数据
    dealResourceData(res.data?.rows)
  }
}

// 处理初始资源数据
const dealResourceData = (data = []) => {
  data = data.map(v => {
    return {
      label: v.roleName || v.fname,
      value: v.roleId || v.fid,
      checked: v.checked
    }
  })
  resourceList.value = data
  checkedRoles.value = data.filter(v => v.checked).map(v => v.value)
  handleCheckedRoleChange(checkedRoles.value)
}

// ---------------------提交数据-------------------
const submitLoading = ref(false)
// 设置提交参数
const setParams = () => {
  const {
    fid,
    accountName,
    realName,
    phone,
    email,
    status
  } = form.value
  return {
    fid: fid,
    faccountName: accountName,
    frealName: realName,
    fphone: phone,
    femail: email,
    fstatus: status,
    fexist: isEdit.value,
    froleIds: checkedRoles.value
  }
}
const handleConfirm = async () => {
  await elFormValidate(formRef.value)
  const params = setParams()
  submitLoading.value = true
  const { res } = await awaitWrap(saveAccountInfo(params))
  if (res?.statusCode === SUCCESS_CODE) {
    showSaveSuccessMessage(res.data)
    emit('dialogConfirmEvent')
    handleClose()
  }
  submitLoading.value = false
}

const showSaveSuccessMessage = (password) => {
  if (isEdit.value) {
    ElMessage.success('操作成功')
  } else {
    ElMessageBox.alert(`账号“${form.value.accountName}”创建成功！初始密码：已通过短信发送至用户的手机，请通知用户及时修改！`, '提示', {
      type: 'success'
    })
  }
}

</script>

<style scoped lang="scss">
@import '@/styles/drawer-base-form.scss';
.tree-wrap{
  background: #f2f2f2;
  padding: 10px;
}
.role-wrap{
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
  .role-item{
    display: flex;
    align-items: center;
    width: 20%;
    .role-label{
      display: block;
      width: 6em;
    }
  }
}
</style>
